//
//  DJSocket.m
//  Pods
//
//  Created by zhenjia zhang on 2017/7/16.
//
//

#import "DJSocket.h"
#import "DJNetWork.h"
#import <DJLog/DJLogManager.h>

@interface DJSocket () {
    DJNetwork *_network;
}
@property (nonatomic, weak)id<DJSocketCallBackProtocol> delegate;
@property (nonatomic, assign)int currentConnectionID;

@end


@implementation DJSocket
+ (instancetype)shareInstance {
    static DJSocket *g_socket;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        g_socket = [DJSocket new];
    });
    return g_socket;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        _network = new DJNetwork();
        _network->init();
        self.currentConnectionID = -1;
    }
    return self;
}

- (void)configWithIP:(NSString *)ip port:(NSInteger)port delegate:(id<DJSocketCallBackProtocol>) delegate {

    DJInfoLog(@"网络库，配置服务器信息，IP：%@ port:%i",ip,port);
    _serverIP = [ip copy];
    _port = port;
    self.delegate = delegate;
    _network->setNetWorkDelegate(delegate);
}

#pragma mark -
#pragma mark - Private API
- (BOOL)connect {
    [self close];
    
    DJInfoLog(@"开始连接 ip：%@, port:%i",self.serverIP,self.port);
    self.currentConnectionID = _network->connect([self.serverIP UTF8String], self.port);
    return self.currentConnectionID != -1;
}

- (void)close {
    DJInfoLog(@"断开连接");
    if (self.currentConnectionID != -1) {
        _network->close(self.currentConnectionID);
        self.currentConnectionID = -1;
    }
}

- (BOOL)sendData:(NSData *)data {
    if (self.currentConnectionID == -1) {
        DJErrorLog(@"发送报文时，连接不存在");
        return NO;
    }
    const char *buf = (const char*)[data bytes];
    DJInfoLog(@"发送报文 大小:%i",[data length]);
    return _network->send(self.currentConnectionID, buf, (int)[data length]);
}

- (DJSocketConnectionStatus)status {
    if (self.currentConnectionID == -1) {
        return DJSocketConnectionStatusClosed;
    }
    return (DJSocketConnectionStatus)_network->getStatus(self.currentConnectionID);
}
@end
